<?php
namespace app\common\library\helper;

use app\common\exception\NException;
use think\Request;
use think\Cache;

class WxHelper
{

    // 获取access_token
    public static function getAccessToken()
    {
        // 优先从缓存获取
        $accessToken = Cache::get('accessToken');
        if(empty($accessToken)) {
            $wx = ConfigHelper::getConfig('wx');
            $result = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wx['appid'] . '&secret=' . $wx['secret']);
            $result = json_decode($result, true);
            if(isset($result['errcode']) || isset($result['errmsg'])) {
                throw new NException( $result['errmsg'] );
            }
            $accessToken = $result['access_token'];
            Cache::set('accessToken', $result['access_token'], 3600);
        }
        return $accessToken;
    }

    // 获取当前关注公众号的用户列表
    public static function userList($access_token, $openid = '')
    {
        $user = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . $access_token . '&next_openid=' . $openid), true);
        if(isset($user['errcode']) || isset($user['errmsg'])) {
            throw new NException( $user['errmsg'] );
        }
        $openidData = $user['data']['openid'];
        // 最后一个用户的OPENID
        $nextOpenid = $user['next_openid'];
        // 获取有几页
        $page = ceil($user['total'] / 10000);

        if($page > 1) {
            for ($i = 1; $i < $page; $i++) {
                $userData = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . $access_token . '&next_openid=' . $nextOpenid), true);
                array_push($openidData, isset($userData['data']) ? $userData['data']['openid'] : '');
                $nextOpenid = $userData['next_openid'];
            }
        }
        return $openidData;
    }

    /**
     * 发送模板消息
     */
    public static function sendNotice(array $data, string $accessToken)
    {
        return json_decode(self::curlPost('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken, json_encode($data)), true);
    }



    /**
     * 传入数组进行HTTP POST请求
     */
    public static function curlPost($url,$data_string,$timeout = 1)
    {
        //curl验证成功
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//// 跳过证书检查
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ));
        if ($timeout > 0) { //超时时间秒
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        }
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}